// 控制器
// author: lbfamous
// date:2020-02-11


cc.Class({
    extends: cc.Component,

    properties: {

        hook:{
            default:null,
            type:cc.Node,
        },

        canvas:{
            default:null,
            type:cc.Node
        },

        speed:350,

        moveToPos:{
            default:cc.v2(0,0),
            visible:false,
        },

        isMoving:{
            default:false,
            visible:false,
        },

        isEnableTouch:{
            default:false,
            visible:false,
        },        
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start () {

        this.enableTouch()

    },

    update (dt) {

        if(!this.isMoving)
            return;
        
        let oldPos = this.node.position;
        let direction = this.moveToPos.sub(oldPos).normalize();
        direction.y = 0;


        let newPos = oldPos.add(direction.mul(this.speed *dt))
        this.node.setPosition(newPos)
    },

    enableTouch() {

        if(this.isEnableTouch)
            return;
        this.hook.on(cc.Node.EventType.TOUCH_START,this.onTouchStart,this);
        this.hook.on(cc.Node.EventType.TOUCH_MOVE,this.onTouchMove,this);
        this.hook.on(cc.Node.EventType.TOUCH_END,this.onTouchEnd,this);
        this.hook.on(cc.Node.EventType.TOUCH_CANCEL,this.onTouchEnd,this);

        this.isEnableTouch = true;
        console.log("enableTouch() -> ");
    },

    disableTouch(){

        if(!this.isEnableTouch)
            return;
        this.hook.off(cc.Node.EventType.TOUCH_START,this.onTouchStart,this);
        this.hook.off(cc.Node.EventType.TOUCH_MOVE,this.onTouchMove,this);
        this.hook.off(cc.Node.EventType.TOUCH_END,this.onTouchEnd,this);
        this.hook.off(cc.Node.EventType.TOUCH_CANCEL,this.onTouchEnd,this);
    },

    onTouchStart(event) {

        let touches = event.getTouches()
        let touchLoc = touches[0].getLocation()
        this.isMoving = true;
        this.moveToPos = this.node.parent.convertToNodeSpaceAR(touchLoc);

    },

    onTouchMove(event){

        let touches = event.getTouches()
        let touchLoc = touches[0].getLocation();
        this.moveToPos = this.node.parent.convertToNodeSpaceAR(touchLoc);

    },

    onTouchEnd(event){

        this.isMoving = false;
    },

    onCollisionEnter(other,self) {
        console.log("onCollisionEnter -> ");
        other.color = cc.Color.RED;

        other.node.color = cc.Color.RED;
        
        let hook = this.hook.getComponent('Hook')
        hook.regainLine();

        other.node.stopAllActions();
        other.node.group = "default";
        other.node.parent = this.node;
        other.node.setPosition(cc.v2(0,0));
        other.node.runAction(cc.repeatForever(cc.sequence(
            cc.rotateTo(0.5,-60 * other.node.scaleX),
            cc.rotateTo(0.5,-30 * other.node.scaleX)
        )));
    },

});
